<?php
/**
 * 图片业务模型处理类
 * @author hary
 */
class upload_model extends Model
{
	public function __construct()
	{
		parent::__construct();

		$this->loadClass('upload');
	}

	/**
	 * 上传图片操作
	 * @param String $form_name 图片在表单中的name值
	 */
	public function upload($form_name,$purpose)
	{

		$fname = array_shift(explode('.',$_FILES[$form_name]['name'])); 
		$new_file_name = time();
							  	  	 					 
		$dir      = $this->sys_conf_var[ 'upload' ]['dir'].'/'.$purpose;
		$filename = upload_file($form_name, $new_file_name, $this->sys_conf_var['upload']['type'], $dir, $this->upload); // 上传操作
		
		if ($filename)
		{
			$ret['url'] 	  = "{$this->sys_conf_var[ 'upload' ]['host']}/{$purpose}/{$filename}";
			$ret['path'] 	  = "{$this->sys_conf_var[ 'upload' ]['dir']}/{$purpose}/{$filename}";
			$imageInfo = getimagesize($ret['path']);
			
			$ret['name']	  = $fname;
			$ret['type']	  = $imageInfo['mime'];
			$ret['size']	  = $_FILES[$form_name]['size'];
			$ret['width']	  = $imageInfo[0];
			$ret['height']	  = $imageInfo[1];
				
			return $ret;
		}

		return false;
	}

	/**
	 * 生成给定大小的缩略图
	 * @param String $half_path
	 * @param Interval $w
	 * @param Interval $h
	 */
	public function makeThumb($half_path, $w, $h, $newName)
	{
		//half_path like /pay/images001.jpg
		$filename   = basename( $half_path );
		$source_dir = $this->sys_conf_var['upload']['dir'] . dirname( $half_path );

		if( !file_exists( $source_dir ) )
		{
			if( !@mkdir($source_dir,0755,1) )
			{
				return false;
			}
		}

		$oImage 		= new images($source_dir . '/', $source_dir . '/');
		$oImage->toFile = true;
		$thumb_path     = $oImage->makeThumb($filename, $w, $h, $newName);

		if ($thumb_path)
		{
			$ret['url'] 	  = "{$this->sys_conf_var[ 'upload' ]['host']}/" . $ret['half_path'];
			$ret['width'] 	  = $w;
			$ret['height']	  = $h;
			$ret['update_date'] = time();
			$ret['name']      = $filename;
			$ret['type']	  = $this->getType($filename);

			return $ret;
		}

		return FALSE;
	}

}